import React, { useState, Suspense } from "react";
import { Link, Routes, Route } from "react-router-dom";

import SubMenu from "./SubMenu";

export default function MenuItem(props: MenuProps) {
  const [expand, setExpand] = useState(false);
  const { id, name, display, permits } = props;
  const relative = name!.substring(name!.lastIndexOf("/") + 1);
  const routePath = relative + "/*";
  const children = permits.filter((p) => p.parentId === id);
  const menuProps = { permits, children };

  const fold = (event: React.MouseEvent) => {
    //event.preventDefault();
    setExpand(!expand);
  }

  const element = () => {
    return expand?<SubMenu {...menuProps}/>:<></>
  };

  return (
    <li>
      <Link onClick={fold} to={name!}>
        {display}
      </Link>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path={routePath} element={element()} />
        </Routes>
      </Suspense>
    </li>
  );
}
